﻿CREATE PROCEDURE sp_ForestReport(@CSVForestList NVARCHAR(MAX))
AS
BEGIN
	DECLARE @Delimiter NVARCHAR(1)
	SET @Delimiter = ','

	DECLARE @QueryString NVARCHAR(MAX)
	SET @QueryString = ''
	WHILE (Charindex(@Delimiter, @CSVForestList)>0)
	BEGIN
		SET @QueryString = @QueryString + 'SELECT * FROM dbo.fn_Forest('''
			+ ltrim(rtrim(Substring(@CSVForestList,1,Charindex(@Delimiter, @CSVForestList) - 1)))
			+ ''') UNION '
		SET @CSVForestList = Substring(@CSVForestList, Charindex(@Delimiter, @CSVForestList) + Len(@Delimiter), Len(@CSVForestList))
	END
	
	SET @QueryString = @QueryString + 'SELECT * FROM dbo.fn_Forest('''
		+ ltrim(rtrim(@CSVForestList)) + ''')'
	PRINT @QueryString
	EXEC [sys].[sp_executesql] @QueryString
END